#!/usr/bin/python
import re
import MySQLdb
from datetime import datetime
from dbquery import executeQuery

query = """ 
  select * from 
    (select off_peak.date_ date_ , (peak.max_ - peak.min_) peak  , (off_peak.max_ - (peak.max_ - peak.min_)) off_peak  
     from 
       (select date(time) date_, min(kwh_today) min_ , max(kwh_today) max_ from solar_data 
         where time(time) > maketime(12,0,0) and time(time) < maketime(18,0,0) and dayofweek(time) != 1 and dayofweek(time) != 7 
         group by date(time)) peak, 
       (select date(time) date_, max(kwh_today) max_ 
         from solar_data 
         where time(time) > maketime(7,0,0) 
         group by date(time)) off_peak 
     where peak.date_ = off_peak.date_ 
    union 
    select date(time) date_, 0 , max(kwh_today) 
      from solar_data 
      where  time(time) > maketime(7,0,0) and (dayofweek(time) = 1 or dayofweek(time) = 7) 
      group by date(time)
    union 
    select date(time) date_, 0 , max(kwh_today) 
      from solar_data 
      where  time(time) > maketime(7,0,0) and dayofweek(time) != 1 and dayofweek(time) != 7 and time(time) < time(now()) and time(time) < maketime(12,0,0) and date(time) = date(now()) and time(now()) < maketime(12,0,0)
      group by date(time)
  ) sub 
  order by sub.date_ desc"""

peak = 0.29372
offPeak = 0.08664
class Money:
    def queryMoney(self):
        return executeQuery(query)

    def computeMoney(self):
        return [ (row[0], row[1] * peak + row[2] * offPeak, row[1], row[2]) for row in self.queryMoney() ]




if __name__ == "__main__":
    money = Money()
    rows = money.queryMoney()
    for row in rows:
        print "%s\t%s\t%s\t%s" % (row[0].strftime("%m-%d-%Y"),row[1], row[2], row[1] + row[2])

    rows = money.computeMoney()
    for row in rows:
        print "%s\t$%s" % (row[0].strftime("%m-%d-%Y"),row[1])
    sum = 0
    for row in rows:
        sum += row[1]
    print "Total: $%s" % (sum)
    rateOfReturn = ((365.0 / len(rows)) * sum) / 20000
    print "Rate of return %.4f%%" % (rateOfReturn * 100)
    def max(x, y): return (x[2] + x[3]) > (y[2] + y[3]) and x or y
    def min(x, y): return (x[2] + x[3]) < (y[2] + y[3]) and x or y
    row = reduce(lambda x,y: (x[2] + x[3]) > (y[2] + y[3]) and x or y, rows)
    print "Max: %s\t%s\t%s" % (row[0].strftime("%m-%d-%Y"),row[1], row[2] + row[3])
    row = reduce(lambda x,y: (x[2] + x[3]) < (y[2] + y[3]) and x or y, rows)
    print "Min: %s\t%s\t%s" % (row[0].strftime("%m-%d-%Y"),row[1], row[2] + row[3])
    
    def m(x): return x[1]
    def add(x,y): return x + y
    print reduce(lambda x,y: x+y,(map(lambda x: x[1], rows)),0)
